﻿using RabbitMQ.Client;
using Server;
using System;
using System.Text;

namespace RouterProducer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("******路由模式生产者*****");

            var msg = "";
            do
            {
                msg = Console.ReadLine(); ;
                Producer.SendQueueMsg(msg);
                Console.WriteLine("******路由消息已经发送*****");

            } while (msg.ToLower() != "out");

            //路由模式就是同过设置RoterKey，只有绑定了相同对应的RoterKey的队列才能触发消费者
        }
    }

    class Producer
    {
        private static readonly ConnectionFactory rabbitMqFactory = CommonConnectionFactory.rabbitMqFactory;

        public static void SendQueueMsg(string msg = "0")
        {
            string ExchangeName = "路由交换机";
            string QueueName = "routerQueue";
            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    //direct：默认，根据routingKey完全匹配，好处是先匹配再发送
                    //topic：根据绑定关键字通配符规则匹配、比较灵活
                    //Fanout：不需要指定routingkey，相当于群发
                    //header：不太常用，可以自定义匹配规则
                    //声明交换机
                    //channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct);
                    //channel.QueueDeclare("路由交换机");

                    channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct, durable: true, autoDelete: false, arguments: null);

                    //未能在路由模式中持久化
                    //channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);
                    //channel.QueueBind(QueueName, ExchangeName, routingKey: "error");
                    var props = channel.CreateBasicProperties();
                    props.Persistent = true;

                    for (int i = 0; i < 10; i++)
                    {
                        //直接发送到交换机，但交换机本身不存储内容，消息数据存在队列中
                        if (i % 2 == 0)
                        {
                            var msgBody = Encoding.UTF8.GetBytes($@"-info{i.ToString()}-");
                            channel.BasicPublish(exchange: ExchangeName, routingKey: "info", basicProperties: props, body: msgBody);
                        }
                        else
                        {
                            var msgBody = Encoding.UTF8.GetBytes($@"-error{i.ToString()}-");
                            channel.BasicPublish(exchange: ExchangeName, routingKey: "error", basicProperties: props, body: msgBody);
                        }
                    }
                    channel.Close();
                }
            }
        }
    }
}
